package com.niodata.dp.task.dao.handler;

import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import com.niodata.dp.task.entity.PluginVersionList;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * plugin version list,column must be  named as VERSIONS.
 */
public class PluginVersionListTypeHandler extends BaseTypeHandler<PluginVersionList>
    implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.VARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return PluginVersionListTypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return PluginVersionList.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, PluginVersionList parameter,
      JdbcType jdbcType) throws SQLException {

  }

  @Override
  public PluginVersionList getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String versions = rs.getString("VERSIONS");
    if (versions != null) {
      String[] versionArray = versions.split(",");
      List<String> list = Arrays.asList(versionArray);
      return new PluginVersionList(list);
    }
    return new PluginVersionList(Collections.emptyList());
  }

  @Override
  public PluginVersionList getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String versions = rs.getString(columnIndex);
    if (versions != null) {
      String[] versionArray = versions.split(",");
      List<String> list = Arrays.asList(versionArray);
      return new PluginVersionList(list);
    }
    return new PluginVersionList(Collections.emptyList());
  }

  @Override
  public PluginVersionList getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    return null;
  }
}
